package beans;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import database.pack.DatabaseConnector;

public class RegistrationBean implements Serializable 
{
	private static final long serialVersionUID = 1L;
	private static int customerID;
	
	public void registerNewUser( String firstName,
								 String lastName,
								 String addressLine1,
								 String addressLine2,
								 String addressLine3,
								 String postcode,
								 String birthDate,
								 String emailAddress,
								 String username,
								 String password )
	{
		try
		{
			DatabaseConnector databaseConnect = new DatabaseConnector();
			databaseConnect.connectToDatabase();
			Statement stat = databaseConnect.getConnection().createStatement();
			ResultSet idResult = stat.executeQuery("SELECT id FROM customer");
			
			while(idResult.next())
			{
				customerID = idResult.getInt("id") + 1;
			}
			
			stat.executeUpdate(
								"INSERT INTO customer" + 
								"(id, firstName, lastName, addressLine1, addressLine2, addressLine3, postcode, birthDate, emailAddress, username, password)" +
								"VALUES (" + 
											customerID + ","	+ 
											"'" + firstName		+ "'," + 
											"'" + lastName		+ "'," + 
											"'" + addressLine1	+ "'," + 
											"'" + addressLine2	+ "'," + 
											"'" + addressLine3	+ "'," + 
											"'" + postcode		+ "'," +
											"'" + birthDate		+ "'," + 
											"'" + emailAddress	+ "'," + 
											"'" + username		+ "'," + 
											"'" + password		+ "')");
			
			stat.close();
			databaseConnect.getConnection().close();
		}
		catch(SQLException exception)
		{
			System.out.println(exception.getMessage());
		}
		catch(ClassNotFoundException e)
		{
			System.out.println("Couldn't connect");
			e.printStackTrace();
		}
	}
	
	public boolean doesUsernameAlreadyExist(String username)
	{
		try
		{
			DatabaseConnector databaseConnect = new DatabaseConnector();
			databaseConnect.connectToDatabase();
			Statement stat = databaseConnect.getConnection().createStatement();
			ResultSet duplicateUser = stat.executeQuery("SELECT username FROM customer");
			while(duplicateUser.next())
			{
				if(username.equals(duplicateUser.getString("username")))
				{
					return true;
				}
			}
		}
		catch(NullPointerException npe)
		{
			// Do nothing
		}
		catch(SQLException exception)
		{
			System.out.println(exception.getMessage());
		}
		catch(ClassNotFoundException e)
		{
			System.out.println("Couldn't connect");
			e.printStackTrace();
		}
		return false;
	}

}
